package cn.iocoder.yudao.gateway.filter.cors;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 跨域 Filter
 * 解决跨域问题
 * 拦截器（Interceptor）是面向 Spring MVC 的，WebFilter 是面向底层 Servlet 或 WebFlux 的
 *
 * @author 芋道源码
 */
@Component
public class CorsFilter implements WebFilter {

    // 允许跨域请求的方式
    private static final String ALL = "*";

    // 允许跨域请求的时长
    private static final String MAX_AGE = "3600L";

    /**
     * Mono<T> 表示 0 或 1 个元素的响应式数据流
     *
     * @param exchange 当前 HTTP 请求 + 响应的上下文对象
     * @param chain    过滤器链，决定是继续放行还是提前结束请求
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        // 非跨域请求，直接放行，
        ServerHttpRequest request = exchange.getRequest();
        if (!CorsUtils.isCorsRequest(request)) {
            return chain.filter(exchange);
        }

        // 设置跨域响应头
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add("Access-Control-Allow-Origin", ALL);
        headers.add("Access-Control-Allow-Methods", ALL);
        headers.add("Access-Control-Allow-Headers", ALL);
        headers.add("Access-Control-Max-Age", MAX_AGE);

        // 如果是预检请求，直接返回 200，表示允许跨域 预检请求（OPTIONS）
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
        return chain.filter(exchange);
    }

}
